package com.apes.autoparts.supplier.dataCenter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.autoparts.supplier.platform.*;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.mq.MQUtil;
import com.apes.framework.util.MapUtil;
import org.elasticsearch.index.IndexNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

/**
 * Created by lishikun on 2021/5/19 17:08
 */
public abstract class DataCenterApi<T, R> extends SupplierPlatformApi<T, R> {

    @Autowired
    SupplierPlatformRepository supplierPlatformRepository;
    @Autowired
    DCBusinessinfoRepository dcBusinessinfoRepository;

    private SupplierPlatform supplierPlatform;

    DataCenterApi(){
        this.source = SupplierPlatformConst.DATA_CENTER;
    }

    private SupplierPlatform getSupplierPlatform() {
        if (this.supplierPlatform != null) return this.supplierPlatform;

        SupplierPlatform supplierPlatform = SpringManager.getBean(SupplierPlatformRepository.class).findOne(
                JpaDsl.toCriteriaByEq(
                        "code", getSource()
                )
        ).orElse(null);
        if (supplierPlatform == null) throw new RuntimeException("未找到当前平台：" + getSource());
        this.supplierPlatform = supplierPlatform;
        return this.supplierPlatform;
    }

    /**
     * 全量
     * @param supplierPlatformItem
     */
    @Override
    public void synTotal(SupplierPlatformItem supplierPlatformItem) {
        if (supplierPlatformItem.getState().equals("debugging")) {
            delete(supplierPlatformItem);
        }
        AllData(supplierPlatformItem, "synTotal");
    }

    /**
     * 增量
     * @param supplierPlatformItem
     */
    @Override
    public void synIncrement(SupplierPlatformItem supplierPlatformItem) {
        String supplierId = "00" + supplierPlatformItem.getSupplierMap().get("id").toString();
        String TS01 = dcBusinessinfoRepository.findMaxTS01BySUPPLIER_ID(supplierPlatformItem.getId()).get(0);
        if (TS01 == null || "".equals(TS01)) return;
        JSONArray param = JSONObject.parseObject(SpringManager.getBean(DomainService.class).invoke("data.center.getBusinessinfoTotal",
                MapUtil.mapper("supplierId", supplierId, "TS01", TS01)).toString()).getJSONArray("body");
        int total = param.getJSONObject(0).getIntValue("TOTAL");
        int size = 500;
        if ( total != 0 ) {
            JSONObject json = new JSONObject();
            for (int page = 0; page  <= total / size; page++) {
                json.put("supplierId", supplierId);
                json.put("PAGE", page);
                json.put("SIZE", size);
                json.put("TS01", TS01);
                JSONArray body = JSONObject.parseObject(SpringManager.getBean(DomainService.class).
                        invoke("data.center.getBusinessinfoPage", json).toString()).getJSONArray("body");
                JSONObject data = new JSONObject();
                data.put("data", body);
                if (page == total / 500) data.put("lastData", true);

                handHeap(supplierPlatformItem, data, "synIncrement");
            }
        }
    }

    @Override
    public R getProductStock(SimpleRequest request) {
        return null;
    }

    @Override
    public void test(SupplierPlatformItem supplierPlatformItem) {

    }

    @Override
    public void simulationApi(SupplierPlatformItem supplierPlatformItem, JSONObject jo) {

    }

    @Override
    public List<Map> getRowData(SupplierPlatformItem supplierPlatformItem, String source) {
        return null;
    }

    @Override
    public void handleRow(SimpleRequest request) {

    }

    public void AllData(SupplierPlatformItem supplierPlatformItem, String action) {
        String supplierId = "00" + supplierPlatformItem.getSupplierMap().get("id").toString();
        JSONArray param = JSONObject.parseObject(SpringManager.getBean(DomainService.class).invoke("data.center.getBusinessinfoTotal",
                MapUtil.mapper("supplierId", supplierId)).toString()).getJSONArray("body");
        int total = param.getJSONObject(0).getIntValue("TOTAL");
        int size = 500;
        if ( total != 0 ) {
            JSONObject json = new JSONObject();
            for (int page = 0; page  <= total / size; page++) {
                json.put("supplierId", supplierId);
                json.put("PAGE", page);
                json.put("SIZE", size);
                JSONArray body = JSONObject.parseObject(SpringManager.getBean(DomainService.class).
                                 invoke("data.center.getBusinessinfoPage", json).toString()).getJSONArray("body");
                JSONObject data = new JSONObject();
                data.put("data", body);

                if (page == total / 500) data.put("lastData", true);
                handHeap(supplierPlatformItem, data, action);
            }

        }
    }

    private void handHeap(SupplierPlatformItem supplierPlatformItem, JSONObject data, String action) {
        String topic;
        if (supplierPlatformItem.getState().equals("debugging")) {
            topic = "auto.dataCenter.debugging";
        } else {
            topic = "auto.dataCenter.handHeap";
        }
        MQUtil.publish(topic, "处理数据中心数据",
        MapUtil.mapper("data", data.getJSONArray("data"),"supplierPlatformItemId",
                supplierPlatformItem.getId(), "action", action, "lastData", data.getBooleanValue("lastData")));
//        SimpleRequest request = new SimpleRequest();
//        request.setData(MapUtil.mapper("data", data.getJSONArray("data"), "supplierPlatformItemId",
//                supplierPlatformItem.getId(), "action", action ,
//                "lastData", data.getBooleanValue("lastData")));
//        SpringManager.getBean(DCBusinessinfoService.class).handHeap(request);
//        SpringManager.getBean(DCBusinessinfoService.class).debugging(request);
    }

    public void delete(SupplierPlatformItem supplierPlatformItem) {
        try {
            SpringManager.getBean(DCBusinessinfoDebugRepository.class).deleteBySupplierPlatformItem(supplierPlatformItem.getId());
        } catch (IndexNotFoundException e) {
            e.printStackTrace();
        }
    }
}
